package com.fanyue.modules.wzb.controller.admin;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fanyue.core.annotation.CoolRestController;
import com.fanyue.core.exception.CoolPreconditions;
import com.fanyue.core.file.FileUploadStrategyFactory;
import com.fanyue.core.request.R;
import com.fanyue.core.util.CoolSecurityUtil;
import com.fanyue.modules.base.dto.sys.BaseDevLoginDto;
import com.fanyue.modules.base.entity.sys.BaseSysParamEntity;
import com.fanyue.modules.base.entity.sys.BaseSysUserEntity;
import com.fanyue.modules.base.service.sys.BaseSysParamService;
import com.fanyue.modules.base.service.sys.BaseSysUserService;
import com.fanyue.modules.user.entity.UserInfoEntity;
import com.fanyue.modules.wzb.entity.AppUserEntity;
import com.fanyue.modules.wzb.entity.AppUserFaceEntity;
import com.fanyue.modules.wzb.entity.AppUserFaceRecordEntity;
import com.fanyue.modules.wzb.service.AppUserFaceRecordService;
import com.fanyue.modules.wzb.service.AppUserFaceService;
import com.fanyue.modules.wzb.service.AppUserService;
import com.fanyue.modules.wzb.service.ClothingInfoService;
import com.fanyue.modules.wzb.utils.FaceApiUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@RequiredArgsConstructor
@Tag(name = "用户信息", description = "用户信息")
@CoolRestController
public class DeviceController {

    private final AppUserService appUserService;
    private final AppUserFaceService appUserFaceService;
    private final BaseSysUserService sysUserService;
    private final AppUserFaceRecordService faceRecordService;
    private final BaseSysParamService sysParamService;
    private final ClothingInfoService clothingInfoService;
    private final FileUploadStrategyFactory fileUploadStrategyFactory;
    private static String filePath = "/data/data/service/api/assets/public";
    //private static String filePath = "D:\\workspace\\fanyue\\storehouse-wzb\\storehouse-wzb-api\\assets\\public";;
    private static String fileUrl = "http://192.168.1.10:8001";
    //private static String fileUrl = "http://127.0.0.1:8001";

    @Operation(summary = "人脸比对")
    @PostMapping("/face/comparison")
    public R comparison(@RequestAttribute JSONObject requestParams) {
        //查询是否，正在批量操作，批量操作期间禁止刷脸
        BaseSysParamEntity baseSysParamEntity = sysParamService.getByKey("clothingIsBatch");
        int isBatch = 0;
        if (ObjectUtil.isEmpty(baseSysParamEntity)) {
            clothingInfoService.replaceIsBatch(isBatch);
        } else {
            isBatch = Integer.parseInt(baseSysParamEntity.getData());
        }
        if (isBatch == 1) {
            return R.error().put("code", 1002).put("message", "正在批量操作，请联系管理员！");
        }

        JSONObject tokenInfo = CoolSecurityUtil.getAdminUserInfo(requestParams);
        BaseSysUserEntity sysUser = sysUserService.getById(tokenInfo.get("userId").toString());
        Integer type = requestParams.getInt("type");
        CoolPreconditions.check(type == null, "缺少参数");
        //开始对比
        Map<String,Object> param = new HashMap<>();
        JSONArray ja = requestParams.getJSONArray("featureData");
        byte[] b = new byte[ja.size()];
        for (int i=0;i<ja.size();i++){
            b[i] = Byte.parseByte(ja.get(i).toString());
        }

        String encodedString = Base64.getEncoder().encodeToString(b);
        param.put("featureData", encodedString);
        try {
            String result = FaceApiUtils.compare(encodedString);
            JSONObject jsonObject = new JSONObject(result);
            Integer code = jsonObject.getInt("code");
            String msg = jsonObject.getStr("message");
            if (code != 200) {
                return R.error(msg);
            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject userInfo = data.getJSONObject("userInfo");
                JSONObject faceSimilar = data.getJSONObject("faceSimilar");

                String userId = userInfo.getStr("id");
                AppUserEntity appUser = appUserService.getById(userId);
                CoolPreconditions.check(ObjectUtil.hasEmpty(appUser) || appUser.getStatus() != 1, "用户信息错误");
                //创建记录,更新时间
                AppUserFaceRecordEntity selectRecord = new AppUserFaceRecordEntity();
                selectRecord.setUserId(appUser.getId());
                selectRecord.setStatus(0);
                List<AppUserFaceRecordEntity> recordEntityList = faceRecordService.listByInfo(selectRecord);
                AppUserFaceRecordEntity record = new AppUserFaceRecordEntity();
                if (recordEntityList.size() > 0 && recordEntityList.get(0).getType().equals(type)) {
                    record = recordEntityList.get(0);
                    record.setDepartmentId(sysUser.getDepartmentId());
                    record.setSysUserId(sysUser.getId());
                    record.setIsSubmit(0);
                    record.setSimilarScore(faceSimilar.getFloat("maxSimilarScore"));
                    faceRecordService.update(record);
                } else {
                    //关闭之前的数据，重新生成
                    faceRecordService.cancel(recordEntityList);
                    record.setUserId(appUser.getId());
                    record.setSimilarScore(faceSimilar.getFloat("maxSimilarScore"));
                    record.setType(type);
                    record.setStatus(0);
                    record.setIsSubmit(0);
                    record.setDepartmentId(sysUser.getDepartmentId());
                    record.setSysUserId(sysUser.getId());
                    faceRecordService.add(record);
                }

                //开始分配
                faceRecordService.distribution(appUser, record);

                String uid = "";
                //显示后六位
                if (appUser.getUid() != null) {
                    if (appUser.getUid().length() > 6) {
                        int length = appUser.getUid().length();
                        uid = appUser.getUid().substring(length - 6);
                    } else {
                        uid = appUser.getUid();
                    }
                }
                appUser.setUid(uid);

                return R.ok().put("appUser", appUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @Operation(summary = "分配被装/货架")
    @PostMapping("/face/distribution")
    public R distribution(@RequestAttribute JSONObject requestParams) {
        //查询是否，正在批量操作，批量操作期间禁止刷脸
        BaseSysParamEntity baseSysParamEntity = sysParamService.getByKey("clothingIsBatch");
        int isBatch = 0;
        if (ObjectUtil.isEmpty(baseSysParamEntity)) {
            clothingInfoService.replaceIsBatch(isBatch);
        } else {
            isBatch = Integer.parseInt(baseSysParamEntity.getData());
        }
        if (isBatch == 1) {
            return R.error().put("code", 1002).put("message", "正在批量操作，请联系管理员！");
        }

        JSONObject tokenInfo = CoolSecurityUtil.getAdminUserInfo(requestParams);
        BaseSysUserEntity sysUser = sysUserService.getById(tokenInfo.get("userId").toString());
        Integer type = requestParams.getInt("type");
        Long userId = requestParams.getLong("userId");
        Float maxSimilarScore = requestParams.getFloat("maxSimilarScore");
        CoolPreconditions.check(type == null, "缺少参数");
        CoolPreconditions.check(userId == null, "缺少参数");
        CoolPreconditions.check(maxSimilarScore == null, "缺少参数");

        AppUserEntity appUser = appUserService.getById(userId);
        CoolPreconditions.check(ObjectUtil.hasEmpty(appUser) || appUser.getStatus() != 1, "用户信息错误");
        //创建记录,更新时间
        AppUserFaceRecordEntity selectRecord = new AppUserFaceRecordEntity();
        selectRecord.setUserId(appUser.getId());
        selectRecord.setStatus(0);
        List<AppUserFaceRecordEntity> recordEntityList = faceRecordService.listByInfo(selectRecord);
        AppUserFaceRecordEntity record = new AppUserFaceRecordEntity();
        if (recordEntityList.size() > 0 && recordEntityList.get(0).getType().equals(type)) {
            record = recordEntityList.get(0);
            record.setDepartmentId(sysUser.getDepartmentId());
            record.setSysUserId(sysUser.getId());
            record.setIsSubmit(0);
            record.setSimilarScore(maxSimilarScore);
            faceRecordService.update(record);
        } else {
            //关闭之前的数据，重新生成
            faceRecordService.cancel(recordEntityList);
            record.setUserId(appUser.getId());
            record.setSimilarScore(maxSimilarScore);
            record.setType(type);
            record.setStatus(0);
            record.setIsSubmit(0);
            record.setDepartmentId(sysUser.getDepartmentId());
            record.setSysUserId(sysUser.getId());
            faceRecordService.add(record);
        }

        //开始分配
        faceRecordService.distribution(appUser, record);

        String uid = "";
        //显示后六位
        if (appUser.getUid() != null) {
            if (appUser.getUid().length() > 6) {
                int length = appUser.getUid().length();
                uid = appUser.getUid().substring(length - 6);
            } else {
                uid = appUser.getUid();
            }
        }
        appUser.setUid(uid);

        return R.ok().put("appUser", appUser);
    }

    @Operation(summary = "借出归还查询")
    @PostMapping("/face/record/list")
    public R faceRecordList(@RequestAttribute JSONObject requestParams) {
        long b = 1739419773308L + 180L * 24 * 60 * 60 * 1000;
        long a = new Date().getTime();
        if (a > b) {
            return R.ok().put("list", null);
        }
        requestParams.set("status", 0);
        return R.ok().put("list", faceRecordService.detailList(requestParams));
    }

    @Operation(summary = "借出归还详情")
    @PostMapping("/face/record/detail")
    public R faceRecordDetail(@RequestAttribute JSONObject requestParams) {
        Long id = requestParams.getLong("id");
        CoolPreconditions.check(id == null, "缺少参数");
        return R.ok().put("info", faceRecordService.detail(id));
    }

    @Operation(summary = "提交记录")
    @PostMapping("/face/record/submit")
    public R faceRecordSubmit(@RequestAttribute JSONObject requestParams) {
        String ids = requestParams.getStr("ids");
        Long recordId = requestParams.getLong("recordId");
        CoolPreconditions.check(StrUtil.isEmpty(ids), "请扫描被装信息");
        CoolPreconditions.check(ObjectUtil.isEmpty(recordId), "缺少操作参数");
        faceRecordService.submit(ids, recordId);
        return R.ok();
    }

    @Operation(summary = "上传人脸")
    @PostMapping("/face/upload/headImage")
    public R faceUploadHeadImage(
            @RequestParam("userId") Long userId,
            @RequestParam("feature") String feature,
            @RequestParam("faceFile") MultipartFile faceFile,
            HttpServletRequest request
    ) {
        AppUserEntity appUser = appUserService.getById(userId);
        if (ObjectUtil.isEmpty(appUser)) {
            return R.error("用户不存在");
        }
        MultipartFile[] files = new MultipartFile[]{faceFile};
        String url = String.valueOf(fileUploadStrategyFactory.upload(files, request));
        if (StrUtil.isEmpty(url)) {
            return R.error("上传失败");
        }

        //Base64加密
        String[] ja = feature.split(",");
        byte[] b = new byte[ja.length];
        for (int i=0;i<ja.length;i++){
            b[i] = Byte.parseByte(ja[i]);
        }
        String encodedString = Base64.getEncoder().encodeToString(b);

        AppUserFaceEntity appUserFace = new AppUserFaceEntity();
        List<AppUserFaceEntity> faceList = appUserFaceService.list(new QueryWrapper()
            .eq("user_id", userId)
        );
        if (faceList.size() > 0) {
            appUserFace = faceList.get(0);
            appUserFace.setFeature(encodedString);
            appUserFace.setStatus(1);
            appUserFace.setIsSync(1);
            appUserFaceService.updateById(appUserFace);
        } else {
            appUserFace.setUserId(userId);
            appUserFace.setFeature(encodedString);
            appUserFace.setStatus(1);
            appUserFace.setIsSync(1);
            appUserFaceService.add(appUserFace);
        }

        appUser.setHeadImage(url);
        appUser.setFaceId(appUserFace.getId());
        appUserService.updateById(appUser);
        return R.ok("保存成功");

        //之前引擎比对使用
        /*AppUserEntity appUser = appUserService.getById(userId);
        if (ObjectUtil.isEmpty(appUser)) {
            return R.error("用户不存在");
        }
        MultipartFile[] files = new MultipartFile[]{faceFile};
        String url = String.valueOf(fileUploadStrategyFactory.upload(files, request));
        if (StrUtil.isEmpty(url)) {
            return R.error("上传失败");
        }
        String fileName = url.replace(fileUrl, filePath);
        File file = new File(fileName);
        try {
            String result = FaceApiUtils.extract(appUser.getId(), file);
            JSONObject jsonObject = new JSONObject(result);
            Integer code = jsonObject.getInt("code");
            String msg = jsonObject.getStr("message");
            if (code != 200) {
                return R.error(msg);
            } else {
                appUser.setHeadImage(url);
                appUserService.updateById(appUser);
                return R.ok("保存成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error("未知错误");*/
    }

    @Operation(summary = "人员信息")
    @PostMapping("/face/appUser/list")
    public R appUserList(@RequestAttribute JSONObject requestParams) {
        return R.ok(appUserService.list(requestParams, new QueryWrapper()));
    }

    @Operation(summary = "人员信息")
    @PostMapping("/face/appUser/page")
    public R appUserPage(@RequestAttribute JSONObject requestParams) {
        Page<AppUserEntity> page = new Page<AppUserEntity>();
        page.setPageNumber(Long.parseLong(requestParams.get("pageNo").toString()));
        page.setPageSize(Long.parseLong(requestParams.get("pageSize").toString()));
        requestParams.set("uidType", "1");
        return R.ok(appUserService.page(requestParams, page, new QueryWrapper()));
    }

    @Operation(summary = "人脸信息")
    @PostMapping("/face/appUserFace/list")
    public R appUserFaceList(@RequestAttribute JSONObject requestParams) {
        return R.ok(appUserFaceService.list(requestParams, new QueryWrapper()));
    }
}
